package controller.servlet.member;

import java.io.IOException;
import java.io.InputStream;
import java.text.ParseException;
import java.util.ArrayList;
import java.util.List;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import model.dao.CategoryDAO;
import model.dao.PostDAO;
import model.dao.service.CategoryDAOService;
import model.dao.service.PostDAOService;
import model.entities.Category;
import model.entities.Post;
import org.apache.commons.fileupload.FileItemIterator;
import org.apache.commons.fileupload.FileItemStream;
import org.apache.commons.fileupload.FileUploadException;
import org.apache.commons.fileupload.servlet.ServletFileUpload;
import util.Constants;

/**
 *
 * @author Khoa
 */
public class MemberPostManagement extends HttpServlet {
     private final PostDAOService POST_SERVICE = PostDAO.getInstance();
    private final CategoryDAOService CATEGORY_SERVICE = CategoryDAO.getInstance();

    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        request.setAttribute(Constants.PAGE, "member_post_management");
        String action = request.getParameter(Constants.ACTION) + "";
        try {
            switch (action) {
                case "delete":
                    deletePost(request);
                    break;
                case "enable":
                    activePost(request, true);
                    refeshList(request);
                    break;
                case "disable":
                    activePost(request, false);
                    refeshList(request);
                    break;
                default:
                    loadPost(request);
                    break;
            }
        } catch (Exception e) {
        }
        request.getRequestDispatcher(Constants.URL_SIDEBAR).forward(request, response);

    }

    /**
     * Handles the HTTP <code>POST</code> method.
     *
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
      request.setAttribute(Constants.PAGE, "member_post_management");
        String action = request.getParameter(Constants.ACTION) + "";
        try {
            switch (action) {
                case "change":
                    changeOffset(request);
                    break;
            }
        } catch (Exception e) {
        }
        request.getRequestDispatcher(Constants.URL_SIDEBAR).forward(request, response);
    }

    private void deletePost(HttpServletRequest request) {
        PostDAOService postService = PostDAO.getInstance();
        try {
            int postID = Integer.parseInt(request.getParameter(Constants.POST_ID));
            if (postService.deletePost(postID)) {
                request.setAttribute(Constants.MSG_RESULT, "Delete success!");
            } else {
                request.setAttribute(Constants.MSG_RESULT, "Delete faile!");
            }
        } catch (Exception e) {
        }
    }

    private void activePost(HttpServletRequest request, boolean isActive) {
        PostDAOService postService = PostDAO.getInstance();
        String result = null;
        try {
            int postID = Integer.parseInt(request.getParameter(Constants.POST_ID));
            if (postService.activePost(isActive, postID)) {
                if (isActive) {
                    result = "Active success!";
                } else {
                    result = "Disactive success";
                }
            } else {
                if (isActive) {
                    result = "Active faile!";
                } else {
                    result = "Disactive falie!";
                }
            }
            request.setAttribute(Constants.MSG_RESULT, result);
        } catch (Exception e) {
        }
    }
    private  void changeOffset(HttpServletRequest request) throws Exception{
        HttpSession session = request.getSession();
        String offset = request.getParameter(Constants.OFFSET);
     //   String currentPage = request.getParameter(Constants.PAGE);
     //  session.setAttribute(Constants.CURRENT_PAGE, currentPage);
        session.setAttribute(Constants.CURRENT_OFFSET, offset);
        refeshList(request);
        
    }
    private void refeshList(HttpServletRequest request) throws Exception{
    }

    private void loadPost(HttpServletRequest request) throws Exception {
        HttpSession session = request.getSession();
        session.setAttribute(Constants.CURRENT_PAGE, request.getParameter(Constants.PAGE));
        session.removeAttribute(Constants.KEY_SEARCH);
        session.removeAttribute(Constants.TYPE_SEARCH);
        PostDAOService postServie = PostDAO.getInstance();
        List<Post> listResultSearch = postServie.getListPost();
        setListPerPage(request, listResultSearch);
    }

    private void setListPerPage(HttpServletRequest request, List<Post> listPost) throws Exception {
        int page = 1, offset = 2;
        try {
            HttpSession session = request.getSession();
            String sPage =(String) session.getAttribute(Constants.CURRENT_PAGE);
            if (sPage != null) {
                page = Integer.parseInt(sPage);
            }
            else
                session.setAttribute(Constants.CURRENT_PAGE,page);
            String sOffset =(String) session.getAttribute(Constants.CURRENT_OFFSET);
            if (sOffset != null) {
                offset = Integer.valueOf(sOffset);
            }
            request.setAttribute(Constants.CURRENT_OFFSET,offset);
            request.setAttribute(Constants.TOTAL_PAGE, Math.ceil(listPost.size() * 1.0 / offset));
            int recordBegin = (page - 1) * offset;
            int recordEnd = recordBegin + offset - 1;
            List<Post> lisPostPerPage = new ArrayList<>();
            for (int i = 0; i < listPost.size(); i++) {
                if (i >= recordBegin && i <= recordEnd) {
                    lisPostPerPage.add(listPost.get(i));
                }
            }
            request.setAttribute(Constants.LIST_POST, lisPostPerPage);
        } catch (Exception e) {
         //   System.out.println(e.toString());
        }
    }
    private void editPost(HttpServletRequest request,HttpServletResponse response)
            throws ServletException, IOException, Exception{
       CategoryDAOService categoryService = CategoryDAO.getInstance();
        String title = null;
        String content = null;
       Category category = null;
        String pathImage = null;
        ServletFileUpload fileUpload = new ServletFileUpload();
        int postID = Integer.parseInt(request.getParameter(Constants.POST_ID));
        try {
            FileItemIterator fit = fileUpload.getItemIterator(request);
            while(fit.hasNext()){
                FileItemStream itemStream = fit.next();
                if(itemStream.isFormField()){
                    String filedName = itemStream.getFieldName();
                    InputStream is = itemStream.openStream();
                    byte[] b = new byte[is.available()];
                    is.read();
                    String value = new String(b);
                    if(filedName.equals("title")){
                        title = value;
                    }
                    if(filedName.equals("content")){
                        content = value;
                    }
                    if(filedName.equals("category")){
                        category = categoryService.getCategoryByName(value);
                    }
                    Post post = new Post(1, title, content, pathImage, null, null, null, true);
                    if(POST_SERVICE.updatePost(post)){
                        response.sendRedirect("/JudBlog"+Constants.URL_POSTMANAGE);
                    } else{
                        request.setAttribute(Constants.MSG_RESULT, "Update faile");
                        request.getRequestDispatcher(Constants.URL_MEMBER).forward(request, response);
                    }
                }
            }
        } catch (FileUploadException | IOException | ParseException e) {
            e.printStackTrace();
        }
        
    }
}
